import os

from django.shortcuts import render

# Create your views here.
from django.template import loader

from django.views.generic import View
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response

from goods.models import GoodsCategory, GoodsChannel, SKU
from contents.models import ContentCategory
from collections import OrderedDict

# Create your views here.
from django.conf import settings

from goods.serializers import SKUSerializer


class CategoryView(View):
    """
    获取首页分类数据

    GET /goods/categories/
    """

    def get(self, request):
        # 使用有序字典保存类别的顺序
        # categories = {
        #     1: { # 组1
        #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
        #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
        #     },
        #     2: { # 组2
        #
        #     }
        # }
        # 初始化存储容器
        categories = OrderedDict()
        # 获取一级分类
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')

        # 对一级分类进行遍历
        for channel in channels:
            # 获取group_id
            group_id = channel.group_id
            # 判断group_id 是否在存储容器,如果不在就初始化
            if group_id not in categories:
                categories[group_id] = {
                    'channels': [],
                    'sub_cats': []
                }

            one = channel.category
            # 为channels填充数据
            categories[group_id]['channels'].append({
                'id': one.id,
                'name': one.name,
                'url': channel.url
            })
            # 为sub_cats填充数据
            for two in one.goodscategory_set.all():
                # 初始化 容器
                two.sub_cats = []
                # 遍历获取
                for three in two.goodscategory_set.all():
                    two.sub_cats.append(three)

                # 组织数据
                categories[group_id]['sub_cats'].append(two)

        # 广告和首页数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        # content_categories = [{'name':xx , 'key': 'index_new'}, {}, {}]

        # {
        #    'index_new': [] ,
        #    'index_lbt': []
        # }
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 组织上下文进行模板渲染
        for aa in contents.get("index_lbt"):
            print(aa)

        context = {
            'categories': categories,
            'contents': contents
        }
        return render(request, 'home.html', context)


"""热销商品"""


class HotSKUView(GenericAPIView):
    """
    GET 请求
    1.根据用户选择的分类的id获取到分类的模型对象
    2.将获取到的对象根据销量进行排序
    3.将模型对象进行序列化,返回前端页面
    # 因为根据id获取到的是所有的商品,而不是分类商品,所以需要重写get_queryset方法
    """
    serializer_class = SKUSerializer

    def get_queryset(self):
        # 获取分类id
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]

    def get(self, request, category_id):
        # 1.获取该分类数据
        skus = self.get_queryset()
        # 2.进行序列化
        serializer = self.get_serializer(skus, many=True)
        # 3.将JSON数据返回前端
        return Response(serializer.data)



"""分类商品列表"""
class SKUListView(ListAPIView):
    """
    GET请求
    1.根据商品分类的id,获取商品,进行序列化
    2.将获取到的商品进行排序
    3.将数据进行分页
    """
    serializer_class = SKUSerializer
    # 3.将获取到的数据进行排序
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    def get_queryset(self):
        # 获取分类id
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id)
    # def get(self,request,category_id):
    #     # 1.根据id获取商品
    #     skus=self.get_queryset()
    #     # 2.将数据进行序列化
    #     serializer=self.get_serializer(skus,many=True)
    #     return Response(serializer.data)

    # 4.数据进行分页(在mall/utils自定义Pagination类)


from .serializers import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer

